package zxing.android;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.virtualapp.R;
import io.virtualapp.bean.UpdateBean;
import io.virtualapp.mylibrary.util.MobileInfoUtils;
import zxing.activity.bean.ListDataSave;
import io.virtualapp.bean.Userbean;
import zxing.camera.CameraManager;
import zxing.view.ViewfinderView;

/**
 * 这个activity打开相机，在后台线程做常规的扫描；它绘制了一个结果view来帮助正确地显示条形码，在扫描的时候显示反馈信息，
 * 然后在扫描成功的时候覆盖扫描结果
 */
public final class CaptureActivity extends Activity implements
        SurfaceHolder.Callback {
    ListDataSave dataSave ;
    private ArrayList<Userbean> listBean;
    private static final String TAG = CaptureActivity.class.getSimpleName();
    Context mContext;
    // 相机控制
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private IntentSource source;
    private Collection<BarcodeFormat> decodeFormats;
    private Map<DecodeHintType, ?> decodeHints;
    private String characterSet;
    // 电量控制
    private InactivityTimer inactivityTimer;
    // 声音、震动控制
    private BeepManager beepManager;

    private ImageButton imageButton_back;

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    /**
     * OnCreate中初始化一些辅助类，如InactivityTimer（休眠）、Beep（声音）以及AmbientLight（闪光灯）
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // 保持Activity处于唤醒状态
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.capture);
        mContext = getApplicationContext();
        hasSurface = false;
        dataSave = new ListDataSave(mContext, "baiyu");
        listBean = new ArrayList<Userbean>();

        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);

        imageButton_back = (ImageButton) findViewById(R.id.capture_imageview_back);
        imageButton_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        // CameraManager必须在这里初始化，而不是在onCreate()中。
        // 这是必须的，因为当我们第一次进入时需要显示帮助页，我们并不想打开Camera,测量屏幕大小
        // 当扫描框的尺寸不正确时会出现bug
        cameraManager = new CameraManager(getApplication());

        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);

        handler = null;

        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            // activity在paused时但不会stopped,因此surface仍旧存在；
            // surfaceCreated()不会调用，因此在这里初始化camera
            initCamera(surfaceHolder);
        } else {
            // 重置callback，等待surfaceCreated()来初始化camera
            surfaceHolder.addCallback(this);
        }

        beepManager.updatePrefs();
        inactivityTimer.onResume();

        source = IntentSource.NONE;
        decodeFormats = null;
        characterSet = null;
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        if (!hasSurface) {
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    /**
     * 扫描成功，处理反馈信息
     *
     * @param rawResult
     * @param barcode
     * @param scaleFactor
     */
    String name, company, email, num, NOTE;

    public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
        inactivityTimer.onActivity();

        boolean fromLiveScan = barcode != null;
        //这里处理解码完成后的结果，此处将参数回传到Activity处理
        if (fromLiveScan) {
            beepManager.playBeepSoundAndVibrate();

            Toast.makeText(this, "扫描成功", Toast.LENGTH_SHORT).show();
            String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))"
                    + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";//设置正则表达式

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
            Date date = new Date(System.currentTimeMillis());
            String n=simpleDateFormat.format(date);
            Userbean user = new Userbean();
            user.setName(n);
            user.setTit(rawResult.getText());
            boolean success = user.save();
            if (success==true){
                Toast.makeText(this, "存储成功", Toast.LENGTH_SHORT).show();
            }
//            listBean.add(user);

            if (rawResult.getText().length() > 6) {
                String s = rawResult.getText().substring(0, 6);
                Pattern pat = Pattern.compile(regex.trim());//比对
                Matcher mat = pat.matcher(rawResult.getText().trim());
                if (mat.matches()) {
                    Uri uri = Uri.parse(rawResult.getText());
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);//打开浏览器
                    startActivity(intent);
                    finish();
                } else if (s.equals("BEGIN:")) {
                    rawResult.getText().replace("TEL;TYPE=CELL:", "TEL:");
                    name = VcardParserUtils.parser(rawResult.getText(), "FN");
                    company = VcardParserUtils.parser(rawResult.getText(), "ORG");
                    email = VcardParserUtils.parser(rawResult.getText(), "EMAIL");
                    num = VcardParserUtils.parser(rawResult.getText(), "TEL");
                    NOTE = VcardParserUtils.parser(rawResult.getText(), "NOTE");
                    if (MobileInfoUtils.getMobileType().equals("OPPO")){
                        Intent intent = new Intent(getApplicationContext(), ScanningResultActivity.class);
                        intent.putExtra("codedContent", rawResult.getText());
                        intent.putExtra("codedBitmap", barcode);
                        startActivity(intent);
                        finish();
                        return;
                    }
                    toContacts();
                    finish();
//                    if (MobileInfoUtils.getMobileType().equals("Xiaomi")){
//                        return;
//                    }else if (MobileInfoUtils.getMobileType().equals("OPPO")){
//                        Intent intent = new Intent(getApplicationContext(), ScanningResultActivity.class);
//                        intent.putExtra("codedContent", rawResult.getText());
//                        intent.putExtra("codedBitmap", barcode);
//                        startActivity(intent);
//                        finish();
//                        return;
//                    }else if (MobileInfoUtils.getMobileType().equals("vivo")){
//                        toContacts();
//                        finish();
//                        return;
//                    }else  if (MobileInfoUtils.getMobileType().equals("HUAWEI")){
//                        toContacts();
//                        finish();
//                        return;
//                    }

                } else {
                    Intent intent = new Intent(getApplicationContext(), ScanningResultActivity.class);
                    intent.putExtra("codedContent", rawResult.getText());//截取字符串
                    intent.putExtra("codedBitmap", barcode);
                    startActivity(intent);
                    finish();
                }
            } else {
                Intent intent = new Intent(getApplicationContext(), ScanningResultActivity.class);
                intent.putExtra("codedContent", rawResult.getText());
                intent.putExtra("codedBitmap", barcode);
                startActivity(intent);
                finish();
            }


        }

    }



    private void toContacts() {

        Intent it = new Intent(Intent.ACTION_INSERT, Uri.withAppendedPath(
                Uri.parse("content://com.android.contacts"), "contacts"));
        it.setType("vnd.android.cursor.dir/person");

// 联系人姓名
        it.putExtra(android.provider.ContactsContract.Intents.Insert.NAME, name);
// 公司
        it.putExtra(android.provider.ContactsContract.Intents.Insert.COMPANY,
                company + "");
// email
        it.putExtra(android.provider.ContactsContract.Intents.Insert.EMAIL,
                email + "");
// 手机号码
        it.putExtra(android.provider.ContactsContract.Intents.Insert.PHONE,
                num + "");
// 单位电话
//        it.putExtra(
//                android.provider.ContactsContract.Intents.Insert.SECONDARY_PHONE,
//                "18600001111");
// 住宅电话
//        it.putExtra(
//                android.provider.ContactsContract.Intents.Insert.TERTIARY_PHONE,
//                "010-7654321");
// 备注信息
        it.putExtra(android.provider.ContactsContract.Intents.Insert.JOB_TITLE,
                "名片");

        startActivity(it);
    }

    /**
     * 初始化Camera
     *
     * @param surfaceHolder
     */
    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            // 打开Camera硬件设备
            cameraManager.openDriver(surfaceHolder);
            // 创建一个handler来打开预览，并抛出一个运行时异常
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats,
                        decodeHints, characterSet, cameraManager);
            }
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    /**
     * 显示底层错误信息并退出应用
     */
    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage(getString(R.string.msg_camera_framework_bug));
        builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
        builder.setOnCancelListener(new FinishListener(this));
        builder.show();
    }

}
